import sys
from PyQt5.QtWidgets import QApplication, QMessageBox, QDialog
from rss_reader.database.database import init_db
from rss_reader.ui.login_dialog import LoginDialog
from rss_reader.ui.main_window import MainWindow
from rss_reader.logger import (logger)  # 导入日志模块

def main():
    logger.info("启动RSS阅读器应用程序")
    app = QApplication(sys.argv)
    logger.debug("初始化数据库连接")
    session_factory = init_db()
    # 显示主窗口
    logger.debug("创建主窗口")
    window = MainWindow(session_factory)
    window.show()
    logger.info("应用程序进入主事件循环")
    sys.exit(app.exec_())

def main_old():
    try:
        logger.info("启动RSS阅读器应用程序")

        app = QApplication(sys.argv)

        # 初始化数据库
        logger.debug("初始化数据库连接")
        session_factory = init_db()

        # 显示登录对话框
        logger.debug("显示登录对话框")
        login_dialog = LoginDialog(session_factory)

        if login_dialog.exec_() == QDialog.Accepted:
            user = login_dialog.authenticated_user
            if user is None:  # 添加检查
                logger.error("登录成功但未获取到用户对象")
                QMessageBox.critical(None, "错误", "登录状态异常")
                return

            logger.info(f"用户 {user.username} 登录成功")

            # 显示主窗口
            logger.debug("创建主窗口")
            window = MainWindow(user, session_factory)
            window.show()

            logger.info("应用程序进入主事件循环")
            sys.exit(app.exec_())

    except Exception as e:
        logger.critical(f"应用程序崩溃: {str(e)}", exc_info=True)
        logger.info("用户取消登录，应用程序退出")

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        logger.critical(f"应用程序崩溃: {str(e)}", exc_info=True)
        raise
